//
// Created by 原帅 on 2021/2/13.
//

#include <RLTaskTest.h>
#include <RLTaskTest2.h>
#include <IERLTaskInitor.h>
#include <IETaskInputReader.h>
#include "IERunloopTaskRepo.h"
#include "IERunLoop.h"
#include "ierunlooprepoid.h"


IERunloopTaskRepo::Builder::Builder() {
    //todo 在这里建立Runloop级Task，并加入到Runloop仓库
    RUNLOOPREPO_ADDTASK(RL_REPO_ID_INITIALIZE,IERLTaskInitor);
    RUNLOOPREPO_ADDTASK(RL_REPO_ID_INPUT_READER,IETaskInputReader);
//    RUNLOOPREPO_ADDTASK(RL_REPO_ID_TASKTEST, RLTaskTest);
//    RUNLOOPREPO_ADDTASK(RL_REPO_ID_TASKTEST2, RLTaskTest2);

}

IERunloopTaskRepo *IERunloopTaskRepo::ieRunloopTaskRepo = 0;
IERunloopTaskRepo *IERunloopTaskRepo::Singelton() {
    if (ieRunloopTaskRepo == nullptr){
        ieRunloopTaskRepo = new IERunloopTaskRepo();
        IERunloopTaskRepo::Builder();
    }
    return ieRunloopTaskRepo;
}

IERunloopTaskRepo::IERunloopTaskRepo() {
}

IERunloopTaskRepo::~IERunloopTaskRepo() {

}

void IERunloopTaskRepo::addTaskToRepo(unsigned long repoid, IERunLoopInterface *anInterface) {
    if (taskRepoMap[repoid]== nullptr){
        taskRepoMap[repoid] = anInterface;
    } else {
        printf("{IERunloopTaskRepo}[%s]: error: repoid: %ld already used!\n",__func__ ,repoid);
    }
}

IERunLoopInterface *IERunloopTaskRepo::getTaskFromRepo(unsigned long repoid) {
    if (taskRepoMap[repoid]!= nullptr) return taskRepoMap[repoid];
    else return nullptr;
}

void IERunloopTaskRepo::scheduleTaskInRunloop(unsigned long repoid) {
    if (this->getTaskFromRepo(repoid)!= nullptr)
        IERunLoop::Singleton()->addTask(this->getTaskFromRepo(repoid));
    else
        printf("{IERunloopTaskRepo}[%s]: error: repoid:%ld not found in repo!\n",__func__ ,repoid);
}

void IERunloopTaskRepo::scheduleTaskOnce(unsigned long repoid) {
    if (this->getTaskFromRepo(repoid)!= nullptr)
        IERunLoop::Singleton()->pushOnceTask(this->getTaskFromRepo(repoid));
    else
        printf("{IERunloopTaskRepo}[%s]: error: repoid:%ld not found in repo!\n",__func__ ,repoid);
}

void IERunloopTaskRepo::removeTaskFromRunloop(unsigned long repoid) {
    if (this->getTaskFromRepo(repoid) != nullptr)
        IERunLoop::Singleton()->removeTaskFromAllRunloop(this->getTaskFromRepo(repoid));
    else
        printf("{IERunloopTaskRepo}[%s]: error: repoid:%ld not found in repo!\n",__func__ ,repoid);
}

